package com.ac.conf;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.GenericFilterBean;

import com.ac.util.IPUtils;

public class IpBlockingFilter extends GenericFilterBean {
	private List<String> blockedIpAddresses = new ArrayList<>();

	public IpBlockingFilter() {
		List<String> blockedIpAddresses = new ArrayList<>();
		blockedIpAddresses.add("192.168.1.33");
		this.blockedIpAddresses = blockedIpAddresses;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		String clientIp = IPUtils.getIpAddr(httpRequest);
		if (blockedIpAddresses.contains(clientIp)) {
			httpResponse.getWriter().write("Access denied for your IP address.");
			httpResponse.setStatus(403);
		} else {
			chain.doFilter(request, response);
		}
	}
}
